/**
 * Copyright @ 2023 iAuto (Shanghai) Co., Ltd.
 * All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are NOT permitted except as agreed by
 * iAuto (Shanghai) Co., Ltd.
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 */

import { useDeepCompareEffect, useReactive, useRequest } from 'ahooks';
import { Button, Col, Radio, Form, Image, Input, message, Row, Select, Modal } from 'antd';

import { useRef, useState } from 'react';
import styles from './edit.less';
import commonStyles from '@/style/common.less';
import React, { useMemo } from 'react';
import {
  editScene,
  getIcon,
  getBackground,
  getScenesDetail,
  getSceneCategory,
} from '@/services/soa/sceneOfficial';
import { router } from 'umi';
import IAutoDetail from '@/components/soa/IAutoDetail';
import { IBackgroundItem, IIConItem, IScenesDetail } from '@/types/sceneOfficial';
import { get01Text } from '@/utils/soa/utils';

const { Item, useForm } = Form;
const { TextArea } = Input;
const { Option } = Select;
const { info } = Modal;

type ValidateStatus = Parameters<typeof Form.Item>[0]['validateStatus'];

// TODO: 类型
const Index = ({ location }: any) => {
  const { query } = location;

  const [form] = useForm();
  const formRef = useRef(null);

  const [nameLength, setNameLength] = useState<number>(0);

  const iconState = useReactive({
    url: '',
  });
  const backgroundState = useReactive({
    url: '',
  });

  const [iconError, setIconError] = useState<ValidateStatus>('success');
  const [backgroundError, setBackgroundError] = useState<ValidateStatus>('success');

  // 场景分类
  const scenesCategoryList = useRequest(getSceneCategory, {
    manual: true,
  });
  // 图标
  const iconList = useRequest(getIcon);
  // 背景图
  const backgroundList = useRequest(getBackground);

  // 请求回来的参数
  const { data, loading: requestLoading } = useRequest(getScenesDetail, {
    defaultParams: [query?.sceneUuid],
  });
  useDeepCompareEffect(() => {
    const seriesCode = data?.data?.seriesCode;
    console.log('seriesCode', seriesCode);
    if (seriesCode) {
      scenesCategoryList.run({
        seriesCode,
      });
    }

    form.setFieldsValue({
      name: data?.data?.name,
      categoryUuid: `${data?.data?.categoryUuid}|${data?.data?.categoryName}`,
      description: data?.data?.description,
      executedOnPhone: data?.data?.executedOnPhone,
      doubleCheckOnVehicle: data?.data?.doubleCheckOnVehicle,
      cycleExecution: data?.data?.cycleExecution,
    });
    setNameLength(data?.data?.name?.length || 0);

    iconState.url = data?.data?.iconUrl || '';
    backgroundState.url = data?.data?.backgroundPicUrl || '';
  }, [data]);

  // 请求回来的参数
  const editRes = useRequest(
    (param: any) => {
      return editScene(param);
    },
    {
      manual: true,
      onSuccess: res => {
        if (res?.statusCode === '0') {
          message.success('保存成功');
          router.push('/soaManage/scene/official/detail?sceneUuid=' + query?.sceneUuid);
        }
      },
    },
  );

  useDeepCompareEffect(() => {
    if (iconState.url) {
      setIconError('success');
    } else {
      setIconError(undefined);
    }
  }, [iconState.url]);

  useDeepCompareEffect(() => {
    if (backgroundState.url) {
      setBackgroundError('success');
    } else {
      setBackgroundError(undefined);
    }
  }, [backgroundState.url]);

  /**
   * @description 保存事件
   */
  const onSave = (values: IScenesDetail) => {
    if (iconError === 'error') {
      return;
    }
    if (backgroundError === 'error') {
      return;
    }
    editRes.run({
      ...data!.data,
      name: values.name,
      description: values?.description || '',
      // categoryUuid: values?.categoryUuid,
      categoryUuid: values?.categoryUuid?.split?.('|')?.[0] || '',
      categoryName: values?.categoryUuid?.split?.('|')?.[1] || '',
      executedOnPhone: values?.executedOnPhone,
      doubleCheckOnVehicle: values?.doubleCheckOnVehicle == null ? 0 : values?.doubleCheckOnVehicle,
      cycleExecution: values?.cycleExecution == null ? 1 : values?.cycleExecution,
      iconUrl: iconState.url,
      backgroundPicUrl: backgroundState.url,
    });
  };

  /**
   * @description form 表单
   */
  const onFormChange = (values: IScenesDetail) => {
    if ('name' in values) {
      setNameLength(values?.name?.length);
    }
    if ('doubleCheckOnVehicle' in values) {
      if (values?.doubleCheckOnVehicle === 0) {
        info({
          content: '该场景在车机端执行时将不会有二次弹窗确认，\n' + '\n' + '请确认。',
        });
      }
    }
  };

  /**
   * @description 选择icon
   */
  const iconClick = (param: IIConItem) => {
    iconState.url = param.url;
  };

  /**
   * @description 选择背景图
   */
  const backgroundClick = (param: IBackgroundItem) => {
    backgroundState.url = param.url;
  };

  /**
   * @description 表单提交
   */
  const onSubmit = () => {
    setIconError(iconState.url === '' ? 'error' : 'success');
    setBackgroundError(backgroundState.url === '' ? 'error' : 'success');
    form.submit();
  };

  const categoryList = useMemo(
    () => (scenesCategoryList?.data?.data ?? []).filter(item => item.name !== '用户共创'),
    [scenesCategoryList],
  );
  return (
    <IAutoDetail className={styles.main} title={'场景编辑'} loading={requestLoading}>
      <Row className={styles.baseInfo}>
        <Col>
          <span>基本信息</span>
        </Col>
      </Row>
      <Form
        form={form}
        ref={formRef}
        onFinish={onSave}
        labelCol={{ span: 2 }}
        wrapperCol={{ span: 18 }}
        onValuesChange={onFormChange}
        labelWrap
        // initialValues={{'cycleExecution':1}}
      >
        <Item
          label="场景名称"
          name="name"
          rules={[
            {
              required: true,
              message: '请填写场景名称！',
            },
            {
              message: '请输入数字、中文、英文！',
              pattern: /^[\u4e00-\u9fa5a-zA-Z\d]{1,12}$/,
            },
          ]}
        >
          <Input
            suffix={<span className={commonStyles.suffixNumber}>{nameLength}/12</span>}
            allowClear
            placeholder={'请输入'}
            maxLength={12}
            className={styles.width580}
          />
        </Item>

        <Item label="场景简介" name="description">
          <TextArea
            maxLength={128}
            placeholder={'请输入'}
            showCount
            rows={5}
            className={styles.width580}
          />
        </Item>

        <Item label="品牌" name="brand">
          <span>{data?.data?.brandName}</span>
        </Item>

        <Item label="车系" name="series">
          <span>{data?.data?.seriesName}</span>
        </Item>

        <Item label="车型" name="model">
          <span className={styles.modelwrap}>{data?.data?.modelName}</span>
        </Item>

        <Item
          label="场景分类"
          name="categoryUuid"
          rules={[
            {
              required: true,
              message: '请选择场景分类！',
            },
          ]}
        >
          <Select className={styles.width580} placeholder={'请选择'}>
            {categoryList?.map?.((item: any) => (
              <Option value={`${item.uuid}|${item.name}`} key={item.uuid}>
                {item.name}
              </Option>
            ))}
          </Select>
        </Item>

        <Item label="是否官方场景" name="officialScene">
          <span>{get01Text(data?.data?.officialScene)}</span>
        </Item>

        <Item label="手机端可执行" name="executedOnPhone">
          <Select className={styles.width580} allowClear placeholder={'请选择'}>
            <Option value={1}>是</Option>
            <Option value={0}>否</Option>
          </Select>
        </Item>

        <Item
          label="车机端二次确认"
          name="doubleCheckOnVehicle"
          rules={[{ required: true, message: '' }]}
          className={data?.data?.haveStartTrigger === 1 ? styles.showInput : styles.hideInput}
        >
          <Select className={styles.width580} allowClear placeholder={'请选择'}>
            <Option value={1}>是</Option>
            <Option value={0}>否</Option>
          </Select>
        </Item>

        <Item
          label={'选择图标'}
          required
          validateStatus={iconError}
          help={iconError === 'error' ? '请选择图标' : ''}
        >
          <div style={{ width: 300 }}>
            {iconList?.data?.data?.map?.((obj: IIConItem) => (
              <Image
                key={obj.uuid}
                src={obj.url}
                preview={false}
                className={`${styles.icon} ${obj.url === iconState.url ? styles.select : ''}`}
                onClick={() => iconClick(obj)}
              />
            ))}
          </div>
        </Item>

        <Item
          label={'选择背景图'}
          required
          validateStatus={backgroundError}
          help={backgroundError === 'error' ? '选择背景图' : ''}
        >
          <div style={{ width: 650 }}>
            {backgroundList?.data?.data?.map?.((obj: IBackgroundItem) => (
              <Image
                key={obj.uuid}
                src={obj.url}
                preview={false}
                className={`${styles.background} ${
                  obj.url === backgroundState.url ? styles.select : ''
                }`}
                onClick={() => backgroundClick(obj)}
              />
            ))}
          </div>
        </Item>

        <Item
          label={'周期内执行次数'}
          extra={'※周期指车辆从上电到下电的时间段'}
          name="cycleExecution"
          rules={[{ required: true, message: '' }]}
          className={data?.data?.haveStartTrigger === 1 ? styles.showInput : styles.hideInput}
        >
          <Radio.Group>
            <Radio value={1}>单次</Radio>
            <Radio value={-1}>无限制</Radio>
          </Radio.Group>
        </Item>

        <Row>
          <Col flex={'none'}></Col>
          <Col flex={'auto'}>
            <Button
              style={{ marginLeft: 30 }}
              onClick={() =>
                router.push('/soaManage/scene/official/detail?sceneUuid=' + query?.sceneUuid)
              }
            >
              取消
            </Button>
            <Button type={'primary'} onClick={onSubmit} style={{ marginLeft: 20 }}>
              保存
            </Button>
          </Col>
        </Row>
      </Form>
    </IAutoDetail>
  );
};

export default Index;
